﻿using System;
using System.Configuration;
using System.Globalization;
using System.Reflection;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using LuxuryResort.WebSite.LRMPDataService;

namespace LuxuryResort.WebSite.Members
{
    public partial class RoomBooking : Page
    {
        private readonly DateTime MaxDate = new DateTime(9999, 1, 1);
        private readonly DateTime MinDate = new DateTime(1900, 1, 1);
        private readonly RoomServiceClient _svc = new RoomServiceClient();

        private Guid UserID
        {
            get
            {
                if (ViewState["UserID"] == null && HttpContext.Current.User != null)
                {
                    string userName = HttpContext.Current.User.Identity.Name;
                    MembershipUser membershipUser = Membership.GetUser(userName);
                    if (membershipUser != null)
                    {
                        object userId = membershipUser.ProviderUserKey;
                        ViewState["UserID"] = userId;
                    }
                }
                return (Guid) ViewState["UserID"];
            }
        }

        private Guid ResortId
        {
            get { return new Guid(ConfigurationManager.AppSettings["ResortId"]); }
        }

        private DateTime CheckIn
        {
            get
            {
                try
                {
                    if (string.IsNullOrEmpty(txtCheckInTime.Text.Trim()))
                    {
                        return MinDate;
                    }
                    return DateTime.ParseExact(txtCheckInTime.Text, "dd/MM/yyyy", CultureInfo.InvariantCulture);
                }
                catch
                {
                    return MinDate;
                }
            }
        }

        private DateTime CheckOut
        {
            get
            {
                try
                {
                    if (string.IsNullOrEmpty(txtCheckOutTime.Text.Trim()))
                    {
                        return MaxDate;
                    }
                    return DateTime.ParseExact(txtCheckOutTime.Text, "dd/MM/yyyy", CultureInfo.InvariantCulture);
                }
                catch
                {
                    return MaxDate;
                }
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                txtCheckInTime.Text = DateTime.Now.ToString("dd/MM/yyyy");
                txtCheckOutTime.Text = DateTime.Now.AddDays(1).ToString("dd/MM/yyyy");
            }
        }

        protected void DataPagerProducts_PreRender(object sender, EventArgs e)
        {
            try
            {
                lvRooms.DataSource = _svc.GetAvailableRooms(UserID, ResortId, CheckIn, CheckOut, ddlRoomType.SelectedValue);
                lvRooms.DataBind();
            }
            catch (Exception ex)
            {
                Response.Redirect("~/AccessDenied.aspx");
            }
            
        }

        protected void lvRooms_ItemCommand(object sender, ListViewCommandEventArgs e)
        {
            if (e.CommandName == "Book")
            {
                BindDataToRoom(e.Item);
            }
        }

        private void BindDataToRoom(ListViewItem item)
        {
            hidRoomID.Value = ((HiddenField) item.FindControl("hidRoomId")).Value;
            hidRoomPrice.Value = ((Label) item.FindControl("lblPrice")).Text;
            lblRoomType.Text = ((Label) item.FindControl("lblRoomType")).Text;
            lblRoomNumber.Text = ((Label) item.FindControl("lblRoomNo")).Text;
            txtCustomerName.Text = string.Empty;
            txtDateFrom.Text = txtCheckInTime.Text;
            txtDateTo.Text = txtCheckOutTime.Text;

            divRoomInformation.Visible = true;
        }

        protected void btnBook_Click(object sender, EventArgs e)
        {
            try
            {
                DateTime checkinDate = DateTime.ParseExact(txtDateFrom.Text, "dd/MM/yyyy", CultureInfo.InvariantCulture);
                DateTime checkoutDate = DateTime.ParseExact(txtDateTo.Text, "dd/MM/yyyy", CultureInfo.InvariantCulture);
                var reservation = new Reservation
                {
                    CreatedAt = DateTime.Now,
                    CreatedBy = UserID,
                    CustomerName = txtCustomerName.Text.Trim(),
                    PaymentMethod = cboPaymentMethod.SelectedValue,
                    Quantity = checkoutDate.Subtract(checkinDate).Days + 1,
                    RMID = new Guid(hidRoomID.Value),
                    RSID = Guid.NewGuid(),
                    CheckIn = DateTime.ParseExact(txtDateFrom.Text, "dd/MM/yyyy", CultureInfo.InvariantCulture),
                    CheckOut = DateTime.ParseExact(txtDateTo.Text, "dd/MM/yyyy", CultureInfo.InvariantCulture),
                    PaymentDone = false,
                    Status = "Booked",
                    Total =
                        !string.IsNullOrEmpty(hidRoomPrice.Value)
                            ? Convert.ToDecimal(hidRoomPrice.Value)*(checkoutDate.Subtract(checkinDate).Days + 1)
                            : 0
                };

                _svc.BookRoom(reservation, UserID, ResortId);

                Page.ClientScript.RegisterStartupScript(GetType(), "showMessage",
                    string.Format("showMessage('{0}')", "Booking done !!!"), true);
            }
            catch (Exception ex)
            {
                Response.Redirect("~/AccessDenied.aspx");
            }
        }

        protected void btnSearch_Click(object sender, EventArgs e)
        {
        }
    }
}